
package botlab.compiler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *  http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
 * @author Quentin
 */
public class MyClassLoader extends ClassLoader
{
    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }
    /** load or reload a class given its url and fully qualified name
     * @param url the absolute path of the file ,ex: "C:/.../MyClass.class"
     * @param fullyQualifiedName = package.name , ex: "mypackage.MyClass"
     * @return the loaded class or null if failure 
     */
    public Class loadClass(String url,String fullyQualifiedName) throws ClassNotFoundException 
    {
        try 
        {
            URL myUrl = new URL("file:"+url);
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while(data != -1){
                buffer.write(data);
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass(fullyQualifiedName,
                    classData, 0, classData.length);

        } 
        catch (IOException ex)
        {
            Logger.getLogger(MyClassLoader.class.getName()).log(Level.SEVERE,
                    null, ex);
        }

        return null;
    }
}
